import styled from 'styled-components';
import React, { CSSProperties, useState, useEffect, useRef } from 'react';

import { ToolsHeader, ObjectRelationGraph, getLayoutedElements } from '../../../../components';
import { metaDataGetObjectRelationsByType } from '../../../../services';

export interface MetaDataObjectAggregationPanelProps {
    style?: CSSProperties;
    objectIdentifier: string;
}

export const MetaDataObjectAggregationPanel: React.FC<MetaDataObjectAggregationPanelProps> = (props) => {

    const [loading, setLoading] = useState<boolean>(false);

    const [nodes, setNodes] = useState([]);

    const [edges, setEdges] = useState([]);

    const [version, setVersion] = useState<number>(0);

    useEffect(() => {
        setLoading(true);
        metaDataGetObjectRelationsByType(props.objectIdentifier, '聚合').then((data) => {
            let nodes = [{
                id: props.objectIdentifier,
                data: { label: props.objectIdentifier },
                type: 'default',
            }].concat(data.map((item, index) => {
                if (item.srcIdentifier === props.objectIdentifier) {
                    return {
                        id: item.targetIdentifier,
                        data: { label: item.targetIdentifier },
                        type: 'output'
                    };
                } else {
                    return {
                        id: item.srcIdentifier,
                        data: { label: item.srcIdentifier },
                        type: 'input'
                    };
                }
            }));

            let edges = data.map((item, index) => {
                let label = '';
                if (item.srcIdentifier === props.objectIdentifier) {
                    label = '聚合';
                } else {
                    label = '聚合';
                }
                return {
                    id: `${item.srcIdentifier}-${item.targetIdentifier}`,
                    source: item.srcIdentifier,
                    target: item.targetIdentifier,
                    label: label,
                    animated: true
                };
            });
            let layout = getLayoutedElements(nodes, edges, 'TB');
            setNodes(layout.nodes);
            setEdges(layout.edges);
            setLoading(false);
            setTimeout(() => {
                setVersion(new Date().getTime());
            }, 100);
        }).catch((err) => {
            console.error(err);
            setLoading(false);
        });
    }, [props.objectIdentifier]);

    if (loading) {
        return (
            <Container style={props.style}>

            </Container>
        );
    }

    return (
        <Container style={props.style}>
            <ObjectRelationGraph style={{
                flex: 1
            }} nodes={nodes} edges={edges} version={version}></ObjectRelationGraph>
        </Container>
    );
}


const Container = styled.div`
    flex:  1;
    width: 100%;
`;
